package com.yonyou.pmclouds.job;

import com.xxl.job.core.executor.XxlJobExecutor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration("pMJobConfiguration")
public class PMJobConfiguration implements BeanPostProcessor {

    public PMJobConfiguration() {

    }
    @Value("${pmcloud.job.admin.addresses}")
    private String adminAddresses;

    @Value("${pmcloud.job.executor.appname}")
    private String appName;

    @Value("${pmcloud.job.executor.ip}")
    private String ip;

    @Value("${pmcloud.job.executor.port}")
    private int port;

    @Value("${pmcloud.job.accessToken}")
    private String accessToken;

    @Value("${pmcloud.job.executor.logpath}")
    private String logPath;

    @Value("${pmcloud.job.executor.logretentiondays}")
    private int logRetentionDays;

    @Bean(initMethod = "start", destroyMethod = "destroy")
    public XxlJobExecutor xxlJobExecutor() {
        XxlJobExecutor xxlJobExecutor = new XxlJobExecutor();
        xxlJobExecutor.setAdminAddresses(adminAddresses);
        xxlJobExecutor.setAppName(appName);
        xxlJobExecutor.setIp(ip);
        xxlJobExecutor.setPort(port);
        xxlJobExecutor.setAccessToken(accessToken);
        xxlJobExecutor.setLogPath(logPath);
        xxlJobExecutor.setLogRetentionDays(logRetentionDays);

        return xxlJobExecutor;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //  注册job
        if (bean instanceof AbstractJobExecutor) {
            String name = beanName;
            JobExecutor info = bean.getClass().getAnnotation(JobExecutor.class);
            if (info != null) {
                name = info.value();
            }
            if (name == null || name.length() == 0) {
                name = beanName;
            }
            if (XxlJobExecutor.loadJobHandler(name) != null) {
                throw new RuntimeException("xxl-job jobhandler naming conflicts.");
            }
            XxlJobExecutor.registJobHandler(name, new JobDelegate(name, (AbstractJobExecutor) bean));
        }
        return bean;
    }
}
